// https://leetcode.cn/problems/fraction-addition-and-subtraction/
// Created by ade on 2022/7/27.
//
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;


class Solution {
public:
    string fractionAddition(string expression) {
        vector<int> molecule = {};
        vector<int> denominator = {};
        int len = expression.size();
        int start = 0;
        int flag = 0;
        // 分隔
        for (int i = 0; i < len; i++) {
            if (expression[i] == '/' && flag == 0) {
                string tmp = expression.substr(start, i - start);
                molecule.push_back(stoi(tmp));
                flag = 1;
                start = i + 1;
                continue;
            }
            if ((expression[i] == '-' || expression[i] == '+') && flag == 1) {
                string tmp = expression.substr(start, i - start);
                denominator.push_back(stoi(tmp));
                flag = 0;
                start = i;
                continue;
            }
        }
        denominator.push_back(stoi(expression.substr(start, len - start)));
        if (denominator.size() == 1) {
            return to_string(molecule[0]) + "/" + to_string(denominator[0]);
        }

        // 最小公约数
        int minDivisor = denominator[0];
        for (int i = 1; i < denominator.size(); i++) {
            if (minDivisor % denominator[i] == 0) {
                continue;
            }
            minDivisor = minDivisor * denominator[i];
        }
        int minDivide = 0;
        for (int i = 0; i < molecule.size(); i++) {
            minDivide += minDivisor/denominator[i]*molecule[i];
        }
        if(minDivide == 0) return "0/1";
        // 去重
        for(int i = abs(minDivide); i >= 2; i--){
            if(minDivide % i == 0 && minDivisor % i == 0 ){
                minDivide /= i;
                minDivisor /= i;
            }
        }

        return to_string(minDivide) + "/" + to_string(minDivisor);
    }
};

int main() {
    Solution so;
    string s1 = "-7/3";
    string s3 = so.fractionAddition(s1);
    cout << s3 << endl;
    return 0;
}